<?php

namespace Tuobaye\FilamentAdmin\Forms;

use Filament\Facades\Filament;
use Filament\Forms\Components\Field;
use Tuobaye\FilamentAdmin\Contracts\HasPermissions;

class PermissionCheckList extends Field
{
    protected string $view = 'filament-admin::forms.components.permission-check-list';

    protected array $permissions = [];

    protected function setUp(): void
    {

        parent::setUp();
        $this->default([]);

        $this->afterStateHydrated(static function (PermissionCheckList $component, $state) {
            if (is_array($state)) {
                return;
            }

            $component->state([]);
        });
    }

    public function getPermissions(): array
    {
        if (!$this->permissions) {
            foreach (Filament::getResources() as $class) {
                if (is_subclass_of($class, HasPermissions::class)) {
                    list($class, $title, $permissions) = $class::allPermissions();
                    $this->permissions[$class] = [
                        'name' => $title,
                        'permissions' => $permissions
                    ];
                }
            }
        }
        return $this->permissions;
    }
}
